import { myRoutes, constantRoutes } from '@/router'
import { getSuper } from '@/utils/auth'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
// function hasPermission(roles, route) {
//   if (route.meta && route.meta.roles) {
//     return roles.some(role => route.meta.roles.includes(role))
//   } else {
//     return true
//   }
// }

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, powers) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    const issuper = getSuper()
    if (issuper === 1 || issuper === '1') {
      res.push(tmp)
    } else {
      const p = powers[tmp.name] || false
      const level = tmp.alwaysShow || false
      if (!level && p) { // 如果是一级菜单，又有该模块
        res.push(tmp)
      } else if (p && tmp.children) { // 如果是有该模块但不是一级菜单
        // 判断所有的二级菜单是否都有权限,没有则剔除
        tmp.children = tmp.children.filter(rou => {
          return p.includes(rou.name) // 返回存在权限的
        })
        res.push(tmp)
      }
    }
  })
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, powers) {
    return new Promise(resolve => {
      const accessedRoutes = filterAsyncRoutes(myRoutes, powers)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  },
  removeAddRoutes({ commit }) {
    commit('SET_ROUTES', [])
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
